//
//  MyViewController.m
//  1gene
//
//  Created by 1jiyin on 16/2/26.
//  Copyright © 2016年 1jiyin. All rights reserved.
//
//***************************我的界面***************************
#import "MyViewController.h"
#import "NoIDViewController.h"
#import "AppDelegate.h"

#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface MyViewController ()<MyTableViewDelegate>
@property(nonatomic,copy)UIView *backGroundView;
@property(nonatomic,copy)UIImageView *backGroundImageView;
@property(nonatomic,assign)CGRect originFrame;
@property(nonatomic,copy)UITextField *userTextField;
@property(nonatomic,copy)UITextField *passwordTextField;
@property(nonatomic,copy)MyTableView *myTable;
@property(nonatomic,assign)CGFloat myScore;

@property(nonatomic,copy)NSDictionary *dataDic;

/*
 *返回的头像
 */
@property(nonatomic,copy)UIImage *userHeadImage;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor colorWithRed:234/255.0 green:235/255.0 blue:236/255.0 alpha:1];
    [self.view addSubview:[UIView new]];
    NSLog(@"我的");
    [self createUI2];
    [self isSetHealthPassword];
    self.navigationController.navigationBar.barStyle=UIBarStyleBlack;
}

-(void)returnScore:(CGFloat)score
{
    _myScore=score;
}

#pragma mark 判断是否是新用户
-(BOOL)isNewUser
{
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *userName=[user stringForKey:@"UserName"];
    NSString *password=[user stringForKey:@"Password"];
    if (userName.length>0&&password.length>0) {
        return NO;
    }else{
        return YES;
    }
}
-(void)createUI2
{
    self.navigationController.navigationBar.hidden=YES;
    self.tabBarController.tabBar.hidden=NO;
    NSArray *arr=@[@"个人资料",@"健康档案",@"我的订单",@"我的收藏",@"关于公司",@"设置与帮助",@"意见反馈"];
    NSArray *imgArr=@[@"75x75-2.png",@"75x75-3.png",@"75x75-1.png",@"75x75-4.png",@"75x75-5.png",@"75x75-6.png",@"shequ_tieba_wodetiezi.png"];
    MyTableView *table=[[MyTableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-10) style:UITableViewStyleGrouped WithData:arr andImgData:imgArr];
    table.myDelegate=self;
    if (_userHeadImage!=nil) {
        table.headImgView.image=_userHeadImage;
    }
    
    [self.view addSubview:table];
    table.getUserInfoData=^(NSDictionary *dic){
        _dataDic=[NSDictionary dictionaryWithDictionary:dic];
    };
    
    
    
    _myTable=table;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//MyTableView的代理--点击用户头像
-(void)userHeadImageViewClick
{
    NSLog(@"实现代理");
    HeadImageSelectedViewController *vc=[[HeadImageSelectedViewController alloc]init];
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=YES;
    vc.returnSelectedImage=^(UIImage *img){
        NSLog(@"图像代理实现了");
        _userHeadImage=img;
        _myTable.headImgView.image=img;
        [self changeUserHeadImage:img];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

//签到
-(void)signIn
{
    [self getSignInHttpData];
}
//抽奖
-(void)choujiang
{
    ChouJiangViewController *vc=[[ChouJiangViewController alloc]init];
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=YES;
    [self.navigationController pushViewController:vc animated:YES];
}
//点击哪一个Cell
-(void)clickCell:(NSInteger)index
{
    if (index==0) {
       //个人资料
        PersonalMessageViewController *vc=[[PersonalMessageViewController alloc]init];
        self.tabBarController.tabBar.hidden=YES;
        self.navigationController.navigationBar.hidden=YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (index==1){
#warning 张国文写的
        // 判断用户是否登录
        if ([NSString stringWithFormat:@"%@", kCurrentUserToken].length == 6 || [kCurrentUserToken isEqualToString:@"(null)"]) {
            // 没登录
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"健康档案必须登录以后才能查看，您现在要登录么" preferredStyle:UIAlertControllerStyleAlert];
            // 修改标题颜色
            NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:@"温馨提示"];
            [titleString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 4)];
            [titleString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 4)];
            [alertVC setValue:titleString forKey:@"attributedTitle"];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
                [delegate showMainViewController:0];
            }];
            [alertVC addAction:sureAction];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertVC addAction:cancelAction];
            [self presentViewController:alertVC animated:YES completion:nil];
        } else {
            //健康档案
            HealthFilesViewController *vc=[[HealthFilesViewController alloc]init];
            self.tabBarController.tabBar.hidden=YES;
            self.navigationController.navigationBar.hidden=NO;
            [self.navigationController pushViewController:vc animated:YES];
        }
       
    }else if (index==2){
        //我的订单
        MyTradeViewController *vc=[[MyTradeViewController alloc]init];
        self.tabBarController.tabBar.hidden=YES;
        self.navigationController.navigationBar.hidden=NO;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index==3){
        //我的收藏
        CollectionViewController *vc=[[CollectionViewController alloc]init];
        self.tabBarController.tabBar.hidden=YES;
        self.navigationController.navigationBar.hidden=NO;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index==4){
        //关于公司
        AbountCompanyViewController *vc=[[AbountCompanyViewController alloc]init];
        self.tabBarController.tabBar.hidden=YES;
        self.navigationController.navigationBar.hidden=NO;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index==5){
        //设置与帮助
        SetAndHelpViewController *vc=[[SetAndHelpViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index==6){
        //意见反馈
        SendSuggestionViewController *vc=[[SendSuggestionViewController alloc]init];
        self.tabBarController.tabBar.hidden=YES;
        self.navigationController.navigationBar.hidden=NO;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

//我的积分
-(void)gotoMyScoreViewController:(CGFloat)score
{
    MyScoreViewController *vc=[[MyScoreViewController alloc]init];
    vc.score=score;
    vc.changeMyScore=^(CGFloat score){
        NSLog(@"%.1f",score);
        _myTable.scoreLab.text=[NSString stringWithFormat:@"积分:%.1f",score];
        _myTable.scoreBtn.tag=score;
        
    };
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=YES;
    [self.navigationController pushViewController:vc animated:YES];
}



//签到
-(void)getSignInHttpData
{
    SignInViewController *vc=[[SignInViewController alloc]init];
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=YES;
    [self.navigationController pushViewController:vc animated:YES];
}


//是否设置健康档案密码
-(void)isSetHealthPassword
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    
    [manager GET:[NSString stringWithFormat:IsSetHealthPassword,token] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dic);
        //[user setBool:YES forKey:@"sethealthPassword"];
        NSInteger isSetHealthPassword=[dic[@"haveprivacypwd"]integerValue];
        NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
        if (isSetHealthPassword==1) {
            [user setBool:YES forKey:@"sethealthPassword"];
        }else{
            [user setBool:NO forKey:@"sethealthPassword"];
        }
        [user synchronize];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error%@",error.localizedDescription);
    }];
    
}

//设置健康档案密码
-(void)setHealthPassword
{
    
}


//更改用户头像
-(void)changeUserHeadImage:(UIImage *)image
{
    
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    [manager POST:[NSString stringWithFormat:ChangeUserHeadImage,token] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            //第一步是将图片转换成二进制数据流
            //NSData * photoData = UIImagePNGRepresentation((id)_dataArray[i]);
            //由于上传的图片是JPG格式的，所以用下面的方法
            NSData * photoData = UIImageJPEGRepresentation(image, 0.5);
            // 获得一个永不重复的随机的字符串
            NSString * imageName =[[NSUUID UUID] UUIDString];
            
            [formData appendPartWithFileData:photoData name:@"avatar" fileName:imageName mimeType:@"image/jpeg"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.view isLoading:NO];
        [self.view showTiShiMessage:@"修改成功"];
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"反馈的信息=====%@",dic);
        if (dic) {
            NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
            [user setObject:dic[@"user"][@"avatar_url"] forKey:@"userHeadImage"];
            [user synchronize];
        }
        
        AppDelegate *app=[UIApplication sharedApplication].delegate;
        [app myClearCacheAction];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view isLoading:NO];
        NSLog(@"error===%@",error.localizedDescription);
    }];

}
-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.view endEditing:YES];
    self.tabBarController.tabBar.hidden=NO;
    self.navigationController.navigationBar.hidden=YES;
    [self.navigationController.navigationBar setTranslucent:YES];
    
    if ([[[NetStatusHandle shareHandle] getUserRegisterIsSucess] isEqualToString:@"YES"]) {
        // 说明注册成功
        [[NetStatusHandle shareHandle] saveUserRegisterIsSuccess:@"NO"];
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertWithAnimationByTitle:@"您可以在个人资料界面完善您的资料" withAniationTime:8 toView:self];
    }
    
    //[self.navigationController.navigationBar setTranslucent:YES];
}



//-(void)viewWillDisappear:(BOOL)animated
//{
//    [self.navigationController.navigationBar setTranslucent:NO];
//}

@end
